<template>
  <div class="spotmall">
    <div :class="isHome ? '' : 'layout-main'">
      <Filtrate @change="filterChange" v-if="!isHome" />
      <div :class="isHome ? '' : 'table_wrapper'">
        <c-table
          ref="spotmallTable"
          :showHeader="isHome ? false : true"
          :showPage="isHome ? false : true"
          :data="tableData.pageData"
          :total="tableData.total"
          :columns="columns"
          rowKey="id"
          expanded
          :loading="loading"
          pagePosition="center"
          @onReload="reload"
          @cellClick="tableRowClick"
          @pageChange="pageChange"
        >
          <template slot="header-l">
            <!-- 排序 -->
            <a-radio-group v-model="sortKey" @change="sortChange">
              <a-radio-button
                v-for="item in sortData"
                :key="item.value"
                :value="item.value"
              >
                {{ item.text }}
              </a-radio-button>
            </a-radio-group>
          </template>
          <template slot="header-r">
            <div class="top_pagination flex flex-align-c">
              <span class="total">共 {{ tableData.total }} 条</span>
              <c-icon
                type="zuo"
                size="16"
                class="cursor-pointer"
                @click.native="setPage(0)"
              ></c-icon>
              <span class="pages no-select">
                <span class="current">{{ pageNum }}</span> /
                <span class="totalPage"
                  >{{ Math.ceil(tableData.total / 20) || 1 }}
                </span>
              </span>
              <c-icon
                type="you"
                class="cursor-pointer"
                @click.native="setPage(1)"
              ></c-icon>
            </div>
          </template>
          <template v-slot:commodity="{ row }">
            <span>{{ row.categoryName }}</span>
            <a-divider type="vertical" />
            <span>{{ row.brand }} </span>
            <span>{{ row.spec }} </span>
            <span>{{ row.material }} </span>
            <span>{{ row.other }} </span>
          </template>
          <template v-slot:priceType="{ row }">
            <TagsPriceType :flag="row" />
          </template>
          <template v-slot:quotationDetailSalesState="{ row }">
            <TagsDetailStatus :flag="row" />
          </template>
          <template v-slot:expirationDate="{ row }">
            {{ $getTime(row) }}
          </template>
          <template v-slot:price="{ row }">
            <Price :data="row" />
          </template>
          <template v-slot:companyName="{ row }">
            <div style="margin-bottom: 4px;">{{ row.companyName }}</div>
            <a-tag color="#1890ff" v-if="row.isProvider">供</a-tag>
            <!-- <a-tooltip placement="top" title="平台精挑细选出来的优质卖家，出售的商品都是精品"> -->
            <a-tag color="LightSeaGreen" v-if="row.isChoicenessSeller"
              >精</a-tag
            >
            <!-- </a-tooltip> -->
          </template>
          <div class="handle" slot="handle" slot-scope="{ row }">
            <!-- <a-dropdown
              v-if="row.priceType === quotationDict.priceType.pricing.value"
            >
              <a-menu slot="overlay">
                <a-menu-item
                  v-for="item in handleMenu"
                  :key="item.title"
                  @click="clickEvent(item.clickEvent, row)"
                >
                  {{ item.title }}
                </a-menu-item>
              </a-menu>
              <a-button size="small">操作 <a-icon type="down"/></a-button>
            </a-dropdown> -->
            <c-button
              type="primary"
              size="small"
              ghost
              @click="orders(row)"
              v-if="row.priceType === quotationDict.priceType.pricing.value"
              >点价采购</c-button
            >
            <c-button
              type="primary"
              size="small"
              ghost
              @click="orders(row)"
              v-if="row.priceType === quotationDict.priceType.confirm.value"
              >下单采购</c-button
            >
          </div>
          <div slot="expanded" slot-scope="row">
            <QuotationExpanded :data="row.row.quotationDO" />
          </div>
        </c-table>
      </div>
    </div>
    <c-modal
      v-model="loginVisible"
      title="请先登录"
      noFooter
      :width="350"
      destroyOnClose
    >
      <Login :isNesting="true" @loginSuccess="loginVisible = false" />
    </c-modal>
  </div>
</template>

<script>
import TagsDetailStatus from "@/components-business/quotation/detailStatus";
import TagsPriceType from "@/components-business/quotation/priceType";
import Price from "@/components-business/quotation/price";
import Filtrate from "./components/filtrate";
import QuotationExpanded from "./components/quotationExpanded";
import Login from "@/page/login/components/contents";
import { getquotations } from "@/api/quotation";
import quotationDict from "@/dict/quotation";
import authDict from "@/dict/auth";
import { mapState, mapActions } from "vuex";
import { debounce, loginDisable } from "@/util/common";
import { uniq } from "lodash";

const sortData = [
  {
    text: "智能排序",
    value: 1
  },
  {
    text: "价格优先",
    value: 2
  },
  {
    text: "数量优先",
    value: 3
  }
];

const columns = [
  {
    title: "商品名称",
    scopedSlots: { customRender: "commodity" }
  },
  {
    title: "仓库",
    dataIndex: "warehouseName"
  },
  {
    title: "数量",
    dataIndex: "amountAvailable"
  },
  {
    title: "作价方式",
    scopedSlots: { customRender: "priceType" }
  },
  {
    title: "价格",
    scopedSlots: { customRender: "price" }
  },
  {
    title: "供应商",
    scopedSlots: { customRender: "companyName" }
  },
  {
    title: "状态",
    dataIndex: "quotationDetailSalesState",
    scopedSlots: { customRender: "quotationDetailSalesState" }
  },
  {
    title: "截止日期",
    dataIndex: "expirationDate",
    scopedSlots: { customRender: "expirationDate" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "handle" }
  }
];

export default {
  components: {
    TagsDetailStatus,
    TagsPriceType,
    Filtrate,
    QuotationExpanded,
    Login,
    Price
  },
  data() {
    return {
      handleMenu: [
        {
          title: "点价采购",
          clickEvent: "orders"
        },
        {
          title: "看行情点价",
          clickEvent: "marketOrders"
        }
      ],
      quotationDict,
      sortData,
      sortKey: 1,
      loading: false,
      tableData: {},
      categoryType: undefined, // 品种分类 1、黑色，2、黑色，3、化工，4、农产品，5、能源，6、其他，全部则不传
      categoryId: undefined, // 品种ID
      pageNum: 1,
      tableDataExpanded: [],
      columns,
      expandedIds: [],
      loginVisible: false
    };
  },
  computed: {
    ...mapState(["user", "search"]),
    // 搜索值
    searchKey() {
      return this.search.searchKey;
    },
    searchStatus() {
      return this.search.searchKeyStatus;
    },
    searchCategory() {
      return this.search.category;
    },
    // 是否在首页
    isHome() {
      return this.$route.name === "home";
    }
  },
  watch: {
    searchStatus() {
      this.reload();
    },
    searchCategory(val) {
      // 重置品种分类
      this.categoryType = undefined;
      this.categoryId = val[1];
      this.reload();
    }
  },
  methods: {
    ...mapActions(["futureWsSend", "setLoginInfo"]),
    // 筛选条件变化时
    filterChange(data) {
      this.pageNum = 1;
      this.categoryType = data.class[0] === 0 ? undefined : data.class[0];
      this.categoryId = data.hotcategory[0];
      this.getQuotations();
    },
    reload() {
      this.pageNum = 1;
      this.getQuotations();
    },
    // 换页
    setPage: debounce(function(type) {
      // 处于第一页时不能往前翻页、处于最后一页时不能往后翻页
      if (
        (this.pageNum === 1 && type === 0) ||
        (this.pageNum === Math.ceil(this.tableData.total / 20) && type === 1)
      ) {
        return false;
      } else {
        let page = type === 0 ? this.pageNum - 1 : this.pageNum + 1;
        this.pageNum = page;
        this.$refs.spotmallTable.setPage(page);
        this.getQuotations();
      }
    }),
    clickEvent(event, row) {
      this[event](row);
    },
    // 下单
    orders(row) {
      // 未登录、未认证、与当前账号相同公司不能进入报价详情
      let _this = this;
      if (!this.$isLogin()) {
        // 是否登录
        if (loginDisable()) {
          this.$warning({
            title: "温馨提示",
            content: "请切换到浏览器已登录商城的标签页进行操作"
          });
        } else {
          this.loginVisible = true;
        }
        // 是否完成认证
      } else if (this.user.authState !== authDict.finish.value) {
        // 是否等待审核或审批
        if (
          this.user.authState === authDict.auditing.value ||
          this.user.authState === authDict.examining.value
        ) {
          this.$warning({
            title: "温馨提示",
            content: "您的身份认证还在审核中，不能进行此操作，请耐心等候。"
          });
        } else {
          this.$confirm({
            title: "温馨提示",
            content: "您还没有身份认证，不能进行此操作，请先申请身份认证！",
            okText: "去认证",
            cancelText: "关闭",
            onOk() {
              // 有进行过身份认证需要标识，用于进到对应认证页弹窗刷脸
              if (_this.user.authState > authDict.unverified.value)
                _this.$storage.s_set("authenticationContinue", true);
              _this.$router.push({ name: "authentication" });
            }
          });
        }
      } else if (this.$sameCompany(row.quotationDO.companyId)) {
        // 是否当前账号公司抬头发布的报价
        this.$warning({
          title: "温馨提示",
          content: "该报价是您公司发布的，不能对自己公司发布的报价点价或下单！"
        });
      } else {
        this.$router.push({
          name: "spotmall-quotation",
          query: { id: row.quotationId, detailId: row.id }
        });
      }
    },
    // 看行情下单
    marketOrders() {},
    sortChange() {
      this.getQuotations();
    },
    // 点击表格行
    tableRowClick({ record }) {
      this.orders(record);
    },
    pageChange(pageNum) {
      this.pageNum = pageNum;
      this.getQuotations();
    },
    // 获取报价列表
    getQuotations() {
      this.loading = true;
      getquotations({
        searchKey: this.searchKey,
        sortType: this.sortKey,
        categoryType: this.categoryType,
        categoryId: this.categoryId,
        pageData: {
          pageNum: this.pageNum,
          pageSize: this.isHome ? 10 : 20
        }
      })
        .then(res => {
          this.tableData = res;
          // 没有数据时，pageData字段没用返回，合约月传空数组
          if (res.pageData) {
            // 当前页合约
            let contracts = uniq(
              res.pageData
                .filter(i => i.futuresContract)
                .map(i => i.futuresContract)
            );
            this.futureWsSend(contracts);
          } else {
            this.futureWsSend([]);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 注册后进入现货商城，提示前往身份认证
    justLogin() {
      let status = this.$route.params.justLogin;
      // 是否存在需要身份认证标识
      if (status) {
        // 是否未完成身份认证
        if (this.user.authState === authDict.unverified.value) {
          let _this = this;
          this.$confirm({
            title: "是否立即进行身份认证？",
            content: "完成身份认证后，才能点价下单。",
            cancelText: "先不认证",
            okText: "立即认证",
            onOk() {
              _this.$router.push({ name: "authentication" });
            }
          });
        }
      }
    },
    // 从登录注册页跳转过来，发起ws连接、存储用户信息
    isLogin() {
      let data = this.$route.params.loginData;
      if (data) {
        this.setLoginInfo(data);
      }
    }
  },
  created() {
    this.isLogin();
    // 是否在全部分类选择品种
    let category = this.$route.params.category;
    if (category) {
      // this.categoryType = category[0]
      this.categoryId = category[1];
    }
    this.justLogin();
    this.getQuotations();
  },
  beforeDestroy() {
    this.futureWsSend([]);
  }
};
</script>

<style lang="scss" scoped>
.spotmall {
  padding-bottom: 20px;
  .table_wrapper {
    padding: 10px 16px;
    position: relative;
    background-color: #fff;
    border-radius: 4px;
    .ant-radio-group-solid
      .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover {
      background: var(--primary);
      border-color: var(--primary);
    }
    ::v-deep .ant-table-row-level-0 {
      position: relative;
    }
    // 主商品表分页居中
    ::v-deep .ant-table-pagination {
      text-align: center;
      float: none;
    }
    .top_pagination {
      .total {
        margin-right: 10px;
      }
      i.iconfont {
        margin: 0 5px;
        font-weight: bold;
      }
    }
    .priceWrapper {
      .bottom {
        font-size: 12px;
      }
    }
  }
}
</style>
